/*
package cn.imokay;

import org.apache.log4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.core.IURIResolver;
import org.apache.poi.xwpf.converter.core.IXWPFConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class ConvertToHtml {

    private static Logger log = Logger.getLogger(ConvertToHtml.class);

    */
/**
     * 根据给定的全路径名，返回文件文本字符串
     *
     * @param filePath html文件全路径名
     * @return html html文件字符串
     *//*

    public static String getExistHtml(String filePath) throws Exception {
        StringBuffer stringBuffer = null;
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(filePath);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String htmlStr = null;
            stringBuffer = new StringBuffer();
            while ((htmlStr = bufferedReader.readLine()) != null) {
                stringBuffer.append(htmlStr);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (fileReader != null) {
                fileReader.close();
            }
        }
        if (stringBuffer == null) {
            throw new RuntimeException("去读html失败");
        }
        return stringBuffer.toString();
    }

    */
/**
     * pdf转html，返回html字符串
     *
     * @param pdfPath   pdf文件全路径名
     * @param outputDir 产出物输出路径（末尾不带'/'）
     * @param url       html中的图片的访问路径前缀
     * @param htmlName  html文件名
     * @return html字符串
     *//*

    public static String pdfToHtml(String pdfPath, String outputDir, String url, String htmlName) throws Exception {
        String htmlFilePath = outputDir + "/" + htmlName;
        File htmlFile = new File(htmlFilePath);
        if (htmlFile.exists()) {
            return getExistHtml(htmlFilePath);
        }
        StringBuffer buffer = new StringBuffer();
        FileOutputStream fos = null;
        PDDocument document = null;
        File pdfFile;
        int size;
        BufferedImage image;
        FileOutputStream out = null;

        File htmlDir = new File(outputDir);
        if (!htmlDir.exists()) {
            htmlDir.mkdirs();
        }

        try {
            //遍历处理pdf附件
            buffer.append("<!doctype html><head><meta charset='UTF-8'></head><body style='background-color:gray;'>" +
                    "<style>img {background-color:#fff; text-align:center; max-width:100%;margin-top:6px;}</style>");
            document = new PDDocument();
            //pdf附件
            pdfFile = new File(pdfPath);
            document = PDDocument.load(pdfFile, (String) null);
            size = document.getNumberOfPages();
            Long start = System.currentTimeMillis(), end = null;
            System.out.println("===>pdf : " + pdfFile.getName() + " , size : " + size);
            PDFRenderer reader = new PDFRenderer(document);
            for (int i = 0; i < size; i++) {
                image = reader.renderImage(i, 1.5f);
                //生成图片,保存位置
                out = new FileOutputStream(outputDir + "/" + "image" + "_" + i + ".jpg");
                ImageIO.write(image, "png", out);
                //将图片路径追加到网页文件里
                String imageStr = "<img src='${url}?ori_file_name=1&file_path=${outputDir}/image_${i}.jpg' height='auto' width='60%'/>";
                imageStr = imageStr.replace("${url}", url).replace("${outputDir}", outputDir).replace("${i}", i + "");
                buffer.append(imageStr);
                image = null;
                out.flush();
                out.close();
            }
            document.close();
            buffer.append("</body></html>");
        } catch (Exception e) {
            log.error("", e);
            throw e;
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (out != null) {
                out.close();
            }
            if (document != null) {
                document.close();
            }
        }
        writeData(htmlFile, buffer.toString());
        return buffer.toString();
    }

    */
/**
     * word2003转html，返回html字符串
     *
     * @param wordPath  pdf文件全路径名
     * @param outputDir 产出物输出路径（末尾不带'/'）
     * @param url       html中的图片的访问路径前缀
     * @param htmlName  html文件名
     * @return html字符串
     *//*

    public static String word2003ToHtml(String wordPath, final String outputDir, final String url, String htmlName) throws Exception {

        //final String imagepath = STORAGEPATH + "fileImage/";//解析时候如果doc文件中有图片  图片会保存在此路径

        //String htmlName = htmlUuidName + ".html";
        File htmlFile = new File(outputDir + "/" + htmlName);
        if (htmlFile.exists()) {
            return getExistHtml(outputDir + "/" + htmlName);
        }

        File imgPathFile = new File(outputDir);
        if (!imgPathFile.exists()) {//图片目录不存在则创建
            imgPathFile.mkdirs();
        }
        InputStream input = new FileInputStream(new File(wordPath));
        HWPFDocument wordDocument = new HWPFDocument(input);
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        //设置图片存放的位置
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                //final String strRanString = getRandomNum();
                File file = new File(outputDir + "/" + suggestedName);
                OutputStream os = null;
                try {
                    os = new FileOutputStream(file);
                    os.write(content);
                } catch (Exception e) {
                    log.error("", e);
                } finally {
                    if (os != null) {
                        try {
                            os.close();
                        } catch (IOException e) {
                            log.error("关闭流失败", e);
                        }
                    }
                }
                return url + "?ori_file_name=1&file_path=" + outputDir + "/" + suggestedName;
            }
        });

        //解析word文档
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();
        OutputStream outStream = null;
        try {
            outStream = new FileOutputStream(htmlFile);

            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(outStream);

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer serializer = factory.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");

            serializer.transform(domSource, streamResult);
        } catch (Exception e) {
            throw e;
        } finally {
            if (outStream != null) {
                outStream.close();
            }
        }
        return getExistHtml(outputDir + "/" + htmlName);
    }

    */
/**
     * word2003转html，返回html字符串
     *
     * @param wordPath  pdf文件全路径名
     * @param outputDir 产出物输出路径（末尾不带'/'）
     * @param url       html中的图片的访问路径前缀
     * @param htmlName  html文件名
     * @return html字符串
     *//*

    public static String word2007ToHtml(String wordPath, final String outputDir, final String url, String htmlName) throws Exception {
        File htmlFile = new File(outputDir + "/" + htmlName);
        if (htmlFile.exists()) {
            return getExistHtml(outputDir + "/" + htmlName);
        }

        // 1) 加载word文档生成 XWPFDocument对象
        InputStream in = new FileInputStream(new File(wordPath));
        XWPFDocument document = new XWPFDocument(in);

        // 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)
        File imageFolderFile = new File(outputDir);
        if (!imageFolderFile.exists()) {
            imageFolderFile.mkdirs();
        }
        XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));
        options.setExtractor(new FileImageExtractor(imageFolderFile));
        options.URIResolver(new IURIResolver() {
            public String resolve(String uri) {
                return url + "?ori_file_name=1&file_path=" + outputDir + "/" + uri;
            }
        });

        options.setIgnoreStylesIfUnused(false);
        options.setFragment(true);

        // 3) 将 XWPFDocument转换成XHTML
        OutputStream out = new FileOutputStream(htmlFile);
        IXWPFConverter<XHTMLOptions> converter = XHTMLConverter.getInstance();
        converter.convert(document, out, options);
        //XHTMLConverter.getInstance().convert(document, out, options);
        return getExistHtml(outputDir + "/" + htmlName);
    }


    */
/**
     * excel转html，返回html字符串
     *
     * @param excelPath excel文件全路径名
     * @param outputDir 产出物输出路径（末尾不带'/'）
     * @param url       html中的图片的访问路径前缀
     * @param htmlName  html文件名
     * @return html字符串
     *//*

    public static String excelToHtml(String excelPath, final String outputDir, final String url, String htmlName) throws Exception {

        File htmlFile = new File(outputDir + "/" + htmlName);
        if (htmlFile.exists()) {
            return getExistHtml(outputDir + "/" + htmlName);
        }

        File outPutFolderFile = new File(outputDir);
        if (!outPutFolderFile.exists()) {
            outPutFolderFile.mkdirs();
        }
        //boolean isWithStyle = true;
        List<Map<String, String>> excelMapList = readExcelToHtml(excelPath, true);
        //System.out.println("excelMapList: " + excelMapList);
        return getHtml(excelMapList, outputDir, url, htmlName);
    }

    private static String getHtml(List<Map<String, String>> excelMapList, String outputDir, String url, String htmlName) throws IOException {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<html><head><title></title><meta charset='UTF-8'></head><body>");
        for (int i = 0; i < excelMapList.size(); i++) {
            String content = excelMapList.get(i).get("content");
            String sheetName = excelMapList.get(i).get("sheetName");
            stringBuffer.append("<h3>")
                    .append(sheetName)
                    .append("</h3>")
                    .append(content)
                    .append("<br/><br/>");
        }

        stringBuffer.append("</body></html>");
        writeData(new File(outputDir + "/" + htmlName), stringBuffer.toString());
        return stringBuffer.toString();
    }

    private static void writeData(File file, String content) throws IOException {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException e) {
            throw e;
        } finally {
            if (fileWriter != null) {
                fileWriter.close();
            }
        }
    }

    */
/**
     * excel转html入口
     *//*

    private static List<Map<String, String>> readExcelToHtml(String filePath, boolean isWithStyle) throws Exception {
        List<Map<String, String>> excelInfoMapList = null;
        // 文件对象
        File file = new File(filePath);
        InputStream inputStream = new FileInputStream(file);

        // 创建工作簿
        Workbook workbook = WorkbookFactory.create(inputStream);
        // Excel类型
        if (workbook instanceof HSSFWorkbook) {
            // 2003
            HSSFWorkbook hssfWorkbook = (HSSFWorkbook) workbook;
            // 获取Excel信息
            excelInfoMapList = getExcelInfo(hssfWorkbook, isWithStyle);
        } else if (workbook instanceof XSSFWorkbook) {
            // 2007
            XSSFWorkbook xssfWorkbook = (XSSFWorkbook) workbook;
            // 获取Excel信息
            excelInfoMapList = getExcelInfo(xssfWorkbook, isWithStyle);
        }


        return excelInfoMapList;
    }

    private static List<Map<String, String>> getExcelInfo(Workbook workbook, boolean isWithStyle) {
        List<Map<String, String>> htmlMapList = new ArrayList<Map<String, String>>();
        // 获取所有sheet
        int sheets = workbook.getNumberOfSheets();
        // 用于计算公式
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
        // 遍历sheets
        for (int sheetIndex = 0; sheetIndex < sheets; sheetIndex++) {
            // 用于保存sheet信息
            Map<String, String> sheetMap = new HashMap<String, String>();
            // 获取sheet名
            String sheetName = workbook.getSheetName(sheetIndex);
            // 存储sheet名
            sheetMap.put("sheetName", sheetName);
            StringBuffer stringBuffer = new StringBuffer();
            // 获取第一个sheet信息
            Sheet sheet = workbook.getSheetAt(sheetIndex);
            // 行数
            int lastRowNum = sheet.getLastRowNum();
            // 获取合并后的单元格行列坐标
            Map<String, String>[] map = getRowSpanColSpan(sheet);
            stringBuffer.append("<table style='border-collapse:collapse;' width='100%'>");
            Row row;
            Cell cell;
            for (int rowNum = sheet.getFirstRowNum(); rowNum <= lastRowNum; rowNum++) {
                row = sheet.getRow(rowNum);
                if (row == null) {
                    stringBuffer.append("<tr><td>&nbsp;</td></tr>");
                    continue;
                }
                stringBuffer.append("<tr>");
                // 列数
                short lastCellNum = row.getLastCellNum();
                for (int colNum = 0; colNum <= lastCellNum; colNum++) {
                    // 获取列
                    cell = row.getCell(colNum);
                    // 空白单元格
                    if (cell == null) {
                        stringBuffer.append("<td>&nbsp;</td>");
                        continue;
                    }
                    // 获取列值
                    String cellValue = getCellValue(cell, evaluator);
                    if (map[0].containsKey(rowNum + "," + colNum)) {
                        String point = map[0].get(rowNum + "," + colNum);
                        map[0].remove(rowNum + "," + colNum);
                        int bottomRow = Integer.valueOf(point.split(",")[0]);
                        int bottomCol = Integer.valueOf(point.split(",")[1]);
                        int rowSpan = bottomRow - rowNum + 1;
                        int colSpan = bottomCol - colNum + 1;
                        stringBuffer.append("<td rowspan= '").append(rowSpan).append("' colSpan= '").append(colSpan).append("' ");
                    } else if (map[1].containsKey(rowNum + "," + colNum)) {
                        map[1].remove(rowNum + "," + colNum);
                        continue;
                    } else {
                        stringBuffer.append("<td ");
                    }

                    // 判断是否包含样式
                    if (isWithStyle) {
                        // 处理单元格样式
                        dealExcelStyle(workbook, sheet, cell, stringBuffer, rowNum == lastRowNum || rowNum > 500);
                    }

                    stringBuffer.append(">");
                    if (cellValue == null || "".equals(cellValue.trim())) {
                        stringBuffer.append(" &nbsp; ");
                    } else {
                        stringBuffer.append(cellValue.replace(String.valueOf((char) 160), "&nbsp;"));
                    }
                    stringBuffer.append("</td>");
                }
                stringBuffer.append("</tr>");
                if (rowNum > 500) {
                    stringBuffer.append("<tr><td colspan= '500'>数据量太大，请下载Excel查看更多数据……</td></tr>");
                    break;
                }
            }
            stringBuffer.append("</table>");
            sheetMap.put("content", stringBuffer.toString());
            htmlMapList.add(sheetMap);
        }
        return htmlMapList;
    }

    private static void dealExcelStyle(Workbook wb, Sheet sheet, Cell cell, StringBuffer sb, boolean isLastRow) {
        CellStyle cellStyle = cell.getCellStyle();
        if (cellStyle != null) {
            short alignment = cellStyle.getAlignment();
            // 单元格内容的水平对齐方式
            sb.append("align='" + convertAlignToHtml(alignment) + "' ");
            short verticalAlignment = cellStyle.getVerticalAlignment();
            // 单元格中内容的垂直排列方式
            sb.append("valign='" + convertVerticalAlignToHtml(verticalAlignment) + "' ");

            if (wb instanceof XSSFWorkbook) {

                XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont();
                boolean isBold = xf.getBold();
                sb.append("style='");
                sb.append("white-space: nowrap; ");
                sb.append("font-weight:" + (isBold ? "bold" : "normal") + "; ");   // 字体加粗
                sb.append("font-size:" + xf.getFontHeight() / 2 + "%; ");   // 字体大小

                XSSFColor xc = xf.getXSSFColor();
                if (xc != null && !"".equals(xc)) {
                    sb.append("color:#" + xc.getARGBHex().substring(2) + "; ");  // 字体颜色
                }

                XSSFColor bgColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
                if (bgColor != null && !"".equals(bgColor)) {
                    sb.append("background-color:#" + bgColor.getARGBHex().substring(2) + "; ");  // 背景颜色
                }
                sb.append(getBorderStyle(0, cellStyle.getBorderTop(), ((XSSFCellStyle) cellStyle).getTopBorderXSSFColor()));
                sb.append(getBorderStyle(1, cellStyle.getBorderRight(), ((XSSFCellStyle) cellStyle).getRightBorderXSSFColor()));
                sb.append(getBorderStyle(3, cellStyle.getBorderLeft(), ((XSSFCellStyle) cellStyle).getLeftBorderXSSFColor()));
                sb.append(getBorderStyle(2, cellStyle.getBorderBottom(), ((XSSFCellStyle) cellStyle).getBottomBorderXSSFColor()));

            } else if (wb instanceof HSSFWorkbook) {

                HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb);
                boolean isBold = hf.getBold();
                short fontColor = hf.getColor();
                sb.append("style='");
                HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette(); // 类HSSFPalette用于求的颜色的国际标准形式
                HSSFColor hc = palette.getColor(fontColor);
                sb.append("font-weight:" + (isBold ? "bold" : "normal") + ";"); // 字体加粗
                sb.append("font-size: " + hf.getFontHeight() / 2 + "%;"); // 字体大小
            }

            sb.append("' ");
        }
    }


    private static String getBorderStyle(int b, short borderStyle, XSSFColor xSSFColor) {

       */
/* short BORDER_NONE = 0;
        short BORDER_THIN = 1;
        short BORDER_MEDIUM = 2;
        short BORDER_DASHED = 3;
        short BORDER_HAIR = 4;
        short BORDER_THICK = 5;
        short BORDER_DOUBLE = 6;
        short BORDER_DOTTED = 7;
        short BORDER_MEDIUM_DASHED = 8;
        short BORDER_DASH_DOT = 9;
        short BORDER_MEDIUM_DASH_DOT = 10;
        short BORDER_DASH_DOT_DOT = 11;
        short BORDER_MEDIUM_DASH_DOT_DOT = 12;
        short BORDER_SLANTED_DASH_DOT = 13;*//*

        if (borderStyle == 0) {
            return borders[b] + "solid" + "#d0d7e5 1px;";
        }
        if (xSSFColor != null) {
            String borderColorStr = xSSFColor.getARGBHex();
            borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000" : borderColorStr.substring(2);
            return borders[b] + "solid" + borderColorStr + " 1px;";
        }

        return "";
    }

    private static String convertVerticalAlignToHtml(short verticalAlignment) {
        */
/*short VERTICAL_TOP = 0;
        short VERTICAL_CENTER = 1;
        short VERTICAL_BOTTOM = 2;
        short VERTICAL_JUSTIFY = 3;
*//*

        String align = "middle";
        switch (verticalAlignment) {
            case 2:
                align = "bottom";
                break;
            case 1:
                align = "center";
                break;
            case 0:
                align = "top";
                break;
            default:
                break;
        }
        return align;
    }


    private static String convertAlignToHtml(short alignment) {

        */
/*short align_general = 0;
        short align_left = 1;
        short align_center = 2;
        short align_right = 3;
        short align_fill = 4;
        short align_justify = 5;
        short align_center_selection = 6;*//*


        String align = "left";
        switch (alignment) {
            case 1:
                align = "left";
                break;
            case 2:
                align = "center";
                break;
            case 3:
                align = "right";
                break;
            default:
                break;
        }
        return align;
    }

    */
/**
     * 获取列值
     *//*

    private static String getCellValue(Cell cell, FormulaEvaluator evaluator) {
        String result;
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_NUMERIC: // 数字类型
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat simpleDateFormat;
                    // 时间
                    if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
                        simpleDateFormat = new SimpleDateFormat("HH:mm");
                    } else {
                        // 日期
                        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    }
                    Date date = cell.getDateCellValue();
                    result = simpleDateFormat.format(date);
                } else if (cell.getCellStyle().getDataFormat() == 58) {
                    // 处理自定义日期格式：m月d日（通过判断单元格格式的id解决，id值为58）
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    double value = cell.getNumericCellValue();
                    Date date = DateUtil.getJavaDate(value);
                    result = simpleDateFormat.format(date);
                } else {
                    double value = cell.getNumericCellValue();
                    CellStyle cellStyle = cell.getCellStyle();
                    DecimalFormat decimalFormat = new DecimalFormat();
                    String temp = cellStyle.getDataFormatString();
                    // 单元格设置成常规
                    if (temp.equals("General")) {
                        decimalFormat.applyPattern("#");
                    }
                    result = decimalFormat.format(value);
                }
                break;
            case HSSFCell.CELL_TYPE_STRING: // 字符串
                result = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_FORMULA: // 公式
                CellValue cellVal = evaluator.evaluate(cell);
                result = (cellVal.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) ? String.valueOf(cellVal.getNumberValue()) : cellVal.getStringValue();
                break;
            default:
                result = "";
                break;
        }
        return result;
    }

    */
/**
     * 合并单元格
     *
     * @return
     *//*

    private static Map<String, String>[] getRowSpanColSpan(Sheet sheet) {
        Map<String, String> map0 = new HashMap<String, String>();
        Map<String, String> map1 = new HashMap<String, String>();
        // 获取合并后的单元格数量
        int mergeNum = sheet.getNumMergedRegions();
        CellRangeAddress range;
        for (int i = 0; i < mergeNum; i++) {
            range = sheet.getMergedRegion(i);
            int topRow = range.getFirstRow();
            int topCol = range.getFirstColumn();
            int bottomRow = range.getLastRow();
            int bottomCol = range.getLastColumn();
            map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol);
            int tempRow = topRow;
            while (tempRow <= bottomRow) {
                int tempCol = topCol;
                while (tempCol <= bottomCol) {
                    map1.put(tempRow + "," + tempCol, "");
                    tempCol++;
                }
                tempRow++;
            }
            map1.remove(topRow + "," + topCol);
        }
        return new Map[]{map0, map1};
    }

    private static String[] borders = {"border-top:", "border-right:", "border-bottom:", "border-left:"};

}
*/
